//
//  TPHomeRootViewController.m
//  Yimei
//
//  Created by xiaowu xiaowu on 2017/10/20.
//  Copyright © 2017年 xiaowu xiaowu. All rights reserved.
//

#import "TPHomeRootViewController.h"
#import "HomeHeaderView.h"
#import "TPHomeCell.h"
#import "TPCityViewController.h"
#import "TPCatesViewController.h"
#import "YPSearchViewController.h"
#import "UISearchBar+TP.h"
#import "TPProductDetailViewController.h"
#import "TPHomeModel.h"
#import "WebViewController.h"
#import "TPCatesTagModel.h"
@interface TPHomeRootViewController ()<UISearchBarDelegate>
@property (nonatomic,strong)NSArray *ads;
@property (nonatomic,strong)HomeHeaderView *headerView;
@property (nonatomic,weak)UISearchBar *searchBar;

@end

@implementation TPHomeRootViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"首页";
    
    [self setupSearch];
    self.tableViewStyle = UITableViewStyleGrouped;
//    self.tableView.backgroundColor = TP_COLOR_245;
    
    _headerView = [[HomeHeaderView alloc]initWithFrame:CGRectMake(0, 0, IPHONE_WIDTH, 1)];
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 50.0, 0);
    self.tableView.tableHeaderView = _headerView;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView reloadData];
    @weakify(self);
    [_headerView setAdBlock:^(NSInteger index, AdsModel *model) {
        DLog(@"---我们");
         @strongify(self);
        
        if(model.type != AdsModelTypeProduct){
            WebViewController *webView = [WebViewController new];
            webView.title = model.title;
            webView.urlstr = model.url;
            webView.html = model.content;
            [self.navigationController pushViewController:webView animated:YES];
        }else{
            
            TPHomeModel *hModel = [[TPHomeModel alloc]init];
            hModel.goods_image = model.img;
            hModel.goods_id = model.gid;
            TPProductDetailViewController *detailVC = [TPProductDetailViewController new];
            detailVC.model =hModel;
            [self.navigationController pushViewController:detailVC animated:YES];
        }
       
    }];
    [_headerView setCateBlock:^(NSIndexPath *indexPath, TPCatesTagModel *model) {
        DLog(@"----%@",model);
        @strongify(self);
        TPCatesViewController *catesVC = [TPCatesViewController new];
        if(indexPath.section == 0 && indexPath.row != 7)
            catesVC.submitModel.gc_id = model.gc_id;
        
        if(indexPath.section == 1 && indexPath.row != 11)
            [catesVC.submitModel.efArray addObject: model];
        
        [self.navigationController pushViewController:catesVC animated:YES];
    }];
    
    
    [self getRequest];
    [self.tableView xw_addPullToRefreshWithHandler:^(UIScrollView *scrollView) {
         @strongify(self);
        self.page = 1;
        [self getRequest];
        [self.headerView reload];
    }];
    
    
    [self.tableView xw_addInfinityScrollWithHandler:^(UIScrollView *scrollView) {
        @strongify(self);
        self.page ++;
        [self getRequest];
    }];
    

}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.searchBar.alpha = 1.0;
    [self.searchBar layoutIfNeeded];
    [self.searchBar.superview layoutIfNeeded];
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.searchBar.alpha = 0.0;
}

-(void)getRequest{
    
    [[TPRequestClient sharedClient]getTemplateListCateId:0 cityName:[XWCommon shareAppDelegate].locationCity goods_salenum:@"" clinic_id:0 name:@"" recommend:true current:self.page size:kMaxRequestSize success:^(NSURLSessionDataTask *task, id responseObject, Responese *respone) {
        
        if(self.page == 1)
            [self.dataSource removeAllObjects];
        NSArray *array = [NSArray yy_modelArrayWithClass:[TPHomeModel class] json:respone.data[@"data"]];
        [self.dataSource addObjectsFromArray:array];
        [self refreshSccuess];
        
    } failure:^(NSURLSessionDataTask *task, NSError *error, Responese *respone) {
        [self refreshFail];
    } nonetWork:^(NSURLSessionDataTask *task, NSError *error) {
        [self refreshFail];
    }];
    
}

-(void)setupSearch{
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, IOS7_TOP_Y-44, IPHONE_WIDTH*0.8, 38.0)];
    self.navigationItem.titleView = view;
    UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, IPHONE_WIDTH*0.7, 34.0)];
    
//    [view addSubview:searchBar];
    self.navigationItem.titleView = searchBar;
    [searchBar setPlaceholder: @"输入关键字进行搜索"];
//    searchBar.backgroundImage = ImageNamed(@"TextFliedclearImage");
    [searchBar setShouldBegindEditingBlock:^BOOL(UISearchBar *earchBar) {
        YPSearchViewController *searchVC = [YPSearchViewController new];
        [self.navigationController pushViewController:searchVC animated:YES];
        return NO;
    }];
    if (@available(iOS 11.0, *)){
        self.navigationItem.hidesSearchBarWhenScrolling = true;
        searchBar.translatesAutoresizingMaskIntoConstraints = false;
        [searchBar.heightAnchor constraintEqualToConstant:44].active = true;
         [searchBar.widthAnchor constraintEqualToConstant:IPHONE_WIDTH*0.7].active=true;
    }
    searchBar.backgroundColor = [UIColor clearColor];
    UITextField *searchField = [searchBar valueForKey:@"searchField"];
    searchField.font = fontSystemOfSize(15.0);
    _searchBar = searchBar;
    
    TPButton *cityButton = [TPButton buttonWithFrame:CGRectMake(10, 0, 80.0, 30.0) title:[XWCommon shareAppDelegate].locationCity font:fontSystemOfSize(15) color:[UIColor whiteColor]];
    [cityButton setImage:[ImageNamed(@"Home_city_down_arrow") imageWithGradientTintColor:[UIColor whiteColor]] forState:UIControlStateNormal];
    cityButton.aligmentType = TPButtonAlignmentTypeCenterRight;
    [cityButton addTouchUpInsideTarget:self action:@selector(pushCityButton:)];
    RAC(cityButton.titleLabel,text) = RACObserve([XWCommon shareAppDelegate], locationCity);
    
    self.navigationItem.rightBarButtonItems = @[[[UIBarButtonItem alloc]initWithCustomView:cityButton]];
    [searchBar layoutIfNeeded];
    [searchBar.superview layoutIfNeeded];
   
    
}
-(void)pushCityButton:(UIButton *)button{
    
    TPCityViewController *cityVC = [TPCityViewController new];
    [self.navigationController pushViewController:cityVC animated:YES];
    [cityVC setSelectBlock:^(NSString *city) {
        [button setTitle:city forState:UIControlStateNormal];
        [XWCommon shareAppDelegate].locationCity = city;
        self.page = 1;
        [self getRequest];
    }];
    
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSource.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    TPHomeCell *cell =[tableView dequeueReusableCellWithIdentifier:@"cellx"];
    if(!cell){
        cell = [[TPHomeCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cellx"];
    }
    cell.indexPath = indexPath;
    cell.model =self.dataSource[indexPath.row];
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    TPProductDetailViewController *detailVC = [TPProductDetailViewController new];
    detailVC.model = self.dataSource[indexPath.row];
    [self.navigationController pushViewController:detailVC animated:YES];
    
}


-(void)getData{
    
    TPHomeModel *model = [TPHomeModel getHomeModelWithName:@"【开内眼角】无创开眼角精细无痕，形态自然，免费设计" price:6800.0 logoPath:@"http://img2.soyoung.com/post/20170801/6/20170801163513109_400.jpg" number:892 array:@[@"自然",@"无痕",@"气质"]];
    
    TPHomeModel *model1 = [TPHomeModel getHomeModelWithName:@"【鼻部】公立三甲主任打造膨体鼻综合，健康，自然，中国好鼻子" price:15000.0 logoPath:@"http://img2.soyoung.com/post/20171018/6/20171018114940967_400.jpg" number:349 array:@[@"无痕",@"气质"]];
    
    TPHomeModel *model2 = [TPHomeModel getHomeModelWithName:@"【吸脂】【单部位减脂】360°立体精细化减脂 完美雕刻曲线" price:680.0 logoPath:@"http://img2.soyoung.com/post/20171115020171115102815252367893990_400.jpg" number:382 array:@[@"减肥",@"魅力"]];
    TPHomeModel *model3 = [TPHomeModel getHomeModelWithName:@"【自体脂肪填充】纳米自体脂肪丰胸，签约效果，上千预约量，一次增大" price:9380.0 logoPath:@"http://img2.soyoung.com/post/20171111420171111172709890692912401_400.jpg" number:2342 array:@[@"丰胸",@"减肥"]];
    TPHomeModel *model4 = [TPHomeModel getHomeModelWithName:@"【自体软骨隆鼻】王院长亲诊~取自身，用自身，安全无排异，不惧揉捏，全耳软骨真鼻~" price:3211 logoPath:@"http://img2.soyoung.com/post/20171114220171114161914911851644956_400.jpg" number:124 array:@[@"隆鼻",@"软骨"]];
    
    [self.dataSource addObject:model];
    [self.dataSource addObject:model1];
    [self.dataSource addObject:model2];
    [self.dataSource addObject:model3];
    [self.dataSource addObject:model4];
    
    [self.tableView reloadData];
}
@end
